package com.xja.seckill.gateway.seckillFilter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

@Component
public class SeckillFilter extends ZuulFilter {

    //创建令牌桶设置容量
    private static final RateLimiter RATE_LIMITER=RateLimiter.create(500);

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override//设置拦截优先级
    public int filterOrder() {
        return SERVLET_DETECTION_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext ();
        HttpServletRequest request = requestContext.getRequest ();
        if (request.getRequestURI ().contains ("/order/createOrder/")){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext ();
        HttpServletResponse response = requestContext.getResponse ();
        //如果没有获取令牌，返回友好提示
        if(!RATE_LIMITER.tryAcquire ()){
            response.setStatus(HttpStatus.SC_ACCEPTED);
        }
        return null;
    }
}
